package com.mediacloud.app.newsmodule.fragment.webview;


import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.view.WebBrowserX;
import com.mediacloud.app.newsmodule.utils.MJavaScriptInterfaceX;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.model.utils.SDKNewsItemJump;
import com.mediacloud.app.model.utils.WebUrlContractParam;
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.model.utils.NeedTokenType;
import com.mediacloud.app.newsmodule.utils.LBSChooseListener;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.NewsUrlFragmentDataInvoker;
import com.mediacloud.app.model.utils.WebViewUtils;
import com.mediacloud.app.model.view.WebBrowser;
import com.mediacloud.app.newsmodule.utils.WebViewLinkCMSNewsHandle;
import com.mediacloud.app.newsmodule.view.LocationChooseHeader;
import com.mediacloud.app.user.broad.LoginBroadcast;
import com.mediacloud.app.user.model.IUserInfo;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.tencent.smtt.sdk.URLUtil;
import com.tencent.smtt.sdk.WebView;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 导航链接新闻
 */
public class NavigateLinkFragment extends WebViewFragment implements LoginBroadcast.UserInfoChanged {
    NewsUrlFragmentDataInvoker fragmentDataInvoker;
    UrlDataCallback urlDataCallback;
    boolean firstPage = true;
    CatalogItem catalogItem;
    boolean isShouldLoadAction = false;
    boolean isSameIdNavigate = false;
    private LoginBroadcast loginBroadcast;

    public NavigateLinkFragment() {
    }

    MJavaScriptInterfaceX mInterface;

    @Override
    public void initView() {
        webPageLoadProgress = findViewById(R.id.webPageLoadProgress);
        mWebBrowser = findViewById(R.id.mWebBrowser);
        broccoli = findViewById(R.id.broccoli);
        mWebBrowser.setHorizontalScrollBarEnabled(false);//水平不显示
        mWebBrowser.setVerticalScrollBarEnabled(false); //垂直不显示
        mInterface = new MJavaScriptInterfaceX(getActivity(), mWebBrowser);
        mWebBrowser.addJavascriptInterface(mInterface, GETMFSIGN);
        mWebBrowser.addJavascriptInterface(mInterface, ANDROID);
        setWebViewParam();
        //	progressDialog=new SimpleDialog(getActivity());
        //	progressDialog.setCancelable(true);
        //	progressDialog.updateText(R.string.hard_loading);

        setLoadImage();
        //		progressDialog.show();
        initWebViewClient();
    }

    @Override
    public void onPause() {
        isSameIdNavigate = false;
        super.onPause();
        tempBeforePauseIsLogin=beforePauseIsLogin;
    }

    String beginUrl;

    @Override
    protected void initWebViewClient() {
        super.initWebViewClient();
        mWebBrowser.setWebViewClient(new WebBrowserX.WebClient(getActivity(), mWebBrowser) {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //	progressDialog.dismiss();
                setLoadImageGone();
                firstPage = false;
                isShouldLoadAction = false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (url.equals(beginUrl))
                {
                    firstPage = false;
                }
                String encodeBeginUrl="";
                try
                {
                    encodeBeginUrl= URLEncoder.encode(beginUrl, "utf-8");

                } catch (Exception e1)
                {
                    e1.printStackTrace();
                    try
                    {
                        encodeBeginUrl = URLEncoder.encode(beginUrl.replaceAll("%25","%"), "utf-8");
                    }
                    catch (Exception e2)
                    {
                        e1.printStackTrace();
                    }
                }
                finally
                {
                    if (url.equals(encodeBeginUrl))
                    {
                        firstPage = false;
                    }
                }
                try
                {
                    url = URLDecoder.decode(url, "utf-8");
                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                    try
                    {
                        url = URLDecoder.decode(url.replaceAll("%", "%25"), "utf-8");
                    }
                    catch (Exception e2)
                    {
                        e1.printStackTrace();
                    }
                }
                finally
                {
                    if (url.equals(beginUrl))
                    {
                        firstPage = false;
                    }
                }
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                WebBrowser.saveCookie(url,view.getContext());
                if(checkWeiMeng(url,view))
                {
                    return true;
                }
                url = WebViewUtils.replaceDoubleQuesMark(url);
                isComplete = false;
                beginUrl = url;
                //调用拨号邮件等程序
//				if (url.startsWith("mailto:") || url.startsWith("geo:") ||url.startsWith("tel:")||url.startsWith("sms:"))
//				{
//					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//					context.startActivity(intent);
//					return true;
//				}
//				else//在导航页面中就打开
                {
                    if (!WebViewLinkCMSNewsHandle.handleCMSNews(url, context, articleItem, catalogItem)&&!SDKNewsItemJump.isMoreFunSDK(context,url)) {
                        if (URLUtil.isNetworkUrl(url)) {
                            Map<String, String> params = WebViewUtils.getUrlParms(url);
                            String key = "logoUrl";//取爆料的分享页面
                            if (params != null && params.containsKey(key) && !TextUtils.isEmpty(params.get(key))) {
                                if (articleItem == null)
                                    articleItem = new ArticleItem();
                                articleItem.setLogo(params.get(key));
                            }
                            isShouldLoadAction = true;
                            //判断后传的 noLogin为true
                            if (WebViewUtils.judgeDelayLoginParam(getActivity(), needToken, params)) {
                                if (WebViewUtils.judgeDelayLoginParamAndRefresh(getActivity(), needToken, params)){
                                    locationUrl = webBrowser.getUrl();
                                }
                                UserInfo userInfo = UserInfo.getUserInfo(getActivity());
                                if (userInfo.isLogin())
                                {
                                    String tempurl = WebUrlContractParam.getContractUserInfoUrl(userInfo, url, getActivity());
                                    if (!firstPage&&!WebViewUtils.isSelfWindow(params))
                                    {
                                        gotoNewNavigateLoadUrl(tempurl);
                                        return true;
                                    }
                                }
                                delayLoginTag = true;
                                locationUrl = url;
                                getLoginInfo();
                                locationUrl = null;
                                return true;
                            } else {
                                //这主要是为了防止重定向
                                WebView.HitTestResult hitTestResult = view.getHitTestResult();
                                Log.w("test", "firstPage:" + firstPage + " hitTestResult.getType()==WebView.HitTestResult.UNKNOWN_TYPE:" + (hitTestResult != null ? (hitTestResult.getType() == WebView.HitTestResult.UNKNOWN_TYPE) + " hitTestResult.type" + hitTestResult.getType() : false));
                                if (firstPage||WebViewUtils.isSelfWindow(params))//||hitTestResult==null||hitTestResult.getType()==WebView.HitTestResult.UNKNOWN_TYPE)
                                {
                                    mWebBrowser.clearHistory();
                                    loadUrl(view, url);
                                    locationUrl = url;
//								firstPage=false;
                                }
                                else
                                {
                                    gotoNewNavigateLoadUrl(url);
                                }
                            }
                        }
                        else
                            matchDefaultUrl(url);
                    }
                    return true;
                }
            }
        });
    }

    @Override
    protected void getLoginInfo() {
        UserInfo userInfo = UserInfo.getUserInfo(getActivity());
        Map<String,String> params=WebViewUtils.getUrlParms(locationUrl);
        if (userInfo.isLogin()) {
            if (TextUtils.isEmpty(locationUrl) == false)
            {
                String tempurl = WebUrlContractParam.getContractUserInfoUrl(userInfo, locationUrl, getActivity());
                beginUrl = tempurl;
                if (firstPage || !isSameIdNavigate||WebViewUtils.isSelfWindow(params))
                {
                    mWebBrowser.clearHistory();
                    mWebBrowser.loadUrl(tempurl);
                    isSameIdNavigate = true;
//					firstPage=false;
                } else {
                    gotoNewNavigateLoadUrl(tempurl);
                }
            }
        } else if (flag) {
            showLoginDialog();
        } else if (delayLoginTag)
        {
            if(hadChoosed)
            {
                firstPage=true;
                goTologin();
            }
        }
        else if (needToken == NeedTokenType.Delayed)
        {
            if (TextUtils.isEmpty(locationUrl) == false)
            {
                String tempurl = WebUrlContractParam.getContract(locationUrl, getActivity());
                beginUrl = tempurl;
                mWebBrowser.clearHistory();
                mWebBrowser.loadUrl(tempurl);
            }
        }
    }

    /**
     * 跳入新的导航页打开url
     *
     * @param url
     */
    protected final void gotoNewNavigateLoadUrl(String url) {
        locationUrl = null;
        ArticleItem articleItem = new ArticleItem();
        articleItem.setIsComment("0");
        articleItem.setLinkNews(false);
        articleItem.setType(TypeX.NEWS.LINK);
        articleItem.setUrl(url);
        if (this.articleItem != null)
            articleItem.setLogo(this.articleItem.getLogo());
//        CatalogItem catalogItem = getFragmentArguments().getParcelable("catalog");
//        articleItem.setTitle(catalogItem.getCatname());
        boolean canCollect = false;
        boolean canShare = true;
        CatalogItem argCatalog=new CatalogItem();
        argCatalog.setCatname(catalogItem.getCatname());
        NewsItemClickUtils.OpenItemNewsHandle(getActivity(), articleItem.getType(), articleItem, argCatalog, needToken, canCollect,canShare);
    }

    boolean hadInvokeUrl = false;

    @Override
    protected void initOther() {
        super.initOther();
        //这是取链接新闻的
        catalogItem = getFragmentArguments().getParcelable("catalog");
        urlDataCallback = new UrlDataCallback();
        fragmentDataInvoker = new NewsUrlFragmentDataInvoker(urlDataCallback);
        if (!hadInvokeUrl && hadChoosed) {
            hadInvokeUrl = true;
            fragmentDataInvoker.getArticleById(catalogItem.getCatid(), /*UserInfo.getUserInfo(getActivity()).getUserid(), */1, 1);
        }
        addLBSChosoeHeader();

        loginBroadcast = new LoginBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LoginBroadcast.SignOut);
        loginBroadcast.userInfoChanged = this;
        getActivity().registerReceiver(loginBroadcast, intentFilter);
    }

    @Override
    public void choosed() {
        super.choosed();
        if (isAdded() && !hadInvokeUrl && fragmentDataInvoker != null) {
            hadInvokeUrl = true;
            fragmentDataInvoker.getArticleById(catalogItem.getCatid(),/* UserInfo.getUserInfo(getActivity()).getUserid(),*/ 1, 1);
        }
    }

    @Override
    public void unChosoed() {
        super.unChosoed();
        if(isAdded()&&getActivity()!=null)
        {
            UserInfo userInfo = UserInfo.getUserInfo(getActivity());
            tempBeforePauseIsLogin = beforePauseIsLogin = userInfo.isLogin();
        }
    }

    protected final void addLBSChosoeHeader() {
        //LBS栏目不为空就加上头
        LocationChooseHeader locationChooseHeader = Utility.findViewById(mRootView, R.id.locationChooseHeader);
        if (catalogItem != null && catalogItem.getLbsItem() != null) {
            int maxLBSH = getActivity().getResources().getDimensionPixelSize(R.dimen.dime_fifty);
            locationChooseHeader.setVisibility(View.VISIBLE);
            locationChooseHeader.catalogItem = catalogItem;
            locationChooseHeader.tag = FGTag.TagID;
            locationChooseHeader.setVisiableHeight(maxLBSH);
        } else
            locationChooseHeader.setVisibility(View.GONE);
    }

    @Override
    protected void showLoginDialog() {
        super.showLoginDialog();
        LocationChooseHeader locationChooseHeader = Utility.findViewById(mRootView, R.id.locationChooseHeader);
        if (locationChooseHeader.getVisibility() == View.VISIBLE) {
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) dialogView.getLayoutParams();
            int pdto = (int) getResources().getDimension(R.dimen.dime_fifty);
            layoutParams.setMargins(layoutParams.leftMargin, pdto, layoutParams.rightMargin, layoutParams.bottomMargin);
        }
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable("catalog", catalogItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy()
    {
        hadInvokeUrl = false;
        if (getActivity() != null && loginBroadcast != null)
            getActivity().unregisterReceiver(loginBroadcast);
        loginBroadcast = null;
        tempBeforePauseIsLogin=beforePauseIsLogin=false;
        fragmentDataInvoker.destory();
        mWebBrowser.removeJavascriptInterface(GETMFSIGN);
        mWebBrowser.removeJavascriptInterface(ANDROID);
        if(mInterface != null){
            mInterface.onDestory();
        }
        super.onDestroy();
    }

    @Override
    public void userSignIn(IUserInfo userInfo) {

    }



    boolean tempBeforePauseIsLogin;
    @Override
    public void userSignOut(Intent intent) {
        boolean isFromNav = intent.getBooleanExtra("isFromNav", true);
        tempBeforePauseIsLogin=beforePauseIsLogin;
        delayLoginTag=false;
        beforePauseIsLogin = false;
        if (!isFromNav)
            firstPage = true;
        isSameIdNavigate = false;
        onResultOrResumeHandle(null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @Override
    public void onResultOrResumeHandle(LoginEvent event)
    {
        isInvokedLogin=false;
        UserInfo userInfo=UserInfo.getUserInfo(getActivity());
        if(needToken==NeedTokenType.Delayed)
        {
            if(tempBeforePauseIsLogin&&!userInfo.isLogin())
            {
                gogo(orginUrl);
                return;
            }
            else if(!tempBeforePauseIsLogin&&userInfo.isLogin())
            {
                gogo(orginUrl);
                return;
            }
            else if(firstPage&&userInfo.isLogin())
            {
                gogo(orginUrl);
                return;
            }
        }else{
            //登录后刷新和退出登录刷新的问题
            if(userInfo.isLogin()){
                mWebBrowser.reload();
            }
//            else{
//                mWebBrowser.loadUrl(orginUrl);
//            }
        }
        super.onResultOrResumeHandle(event);
    }

    String orginUrl;
    protected void gogo(String url)
    {
        locationUrl = WebUrlContractParam.getContract(url, getActivity());
        //如果是立马要token信息的
        if (needToken == NeedTokenType.RightNow)
        {
            flag = true;
            getLoginInfo();
        }
        else if (needToken == NeedTokenType.Delayed)
        {
            getLoginInfo();
        }
        else if (TextUtils.isEmpty(locationUrl) == false)
        {
            mWebBrowser.clearHistory();
            mWebBrowser.loadUrl(locationUrl);
        }
    }


    class UrlDataCallback implements DataInvokeCallBack<BaseMessageReciver> {

        @Override
        public void success(BaseMessageReciver result) {
            // TODO Auto-generated method stub
            Log.w(TAG, "" + result);
            if (result.state) {
                firstPage = true;
                JSONObject data = result.orginData.optJSONObject("data");
                if (FloatButtonGroup.haveFloatField(data)) {
                    initFloatWin(data);
                } else {
                    hideFloatWin();
                }
                if (data != null && !TextUtils.isEmpty(data.optString("url"))) {
                    locationUrl = data.optString("url");
                    orginUrl=locationUrl;
                    needToken = data.optInt("tag", NeedTokenType.Unnecessary);
                    beginUrl = locationUrl;
                    gogo(locationUrl);
                }
                if (isHidden()) {
                    onHiddenChanged(true);
                }
            } else {
                if (!fragmentDataInvoker.isDisposed())
                    fragmentDataInvoker.getArticleById(catalogItem.getCatid(), /*UserInfo.getUserInfo(getActivity()).getUserid(),*/ 1, 1);
            }
        }

        @Override
        public void fault(Object data) {
            if (fragmentDataInvoker.isDisposed())
                return;
            fragmentDataInvoker.getArticleById(catalogItem.getCatid(), /*UserInfo.getUserInfo(getActivity()).getUserid(),*/ 1, 1);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == LOGIN_CODE && resultCode == Activity.RESULT_OK) {
            String fragmentId = data.getStringExtra("id");
            isSameIdNavigate = FGTag.TagID.equals(fragmentId);
        }
        if (data != null && requestCode == LBSChooseListener.Request && resultCode == Activity.RESULT_OK)
            LBSChooseListener.getInstance().onActivityResult(data, this);
    }
}